package com.qianfeng.user.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qianfeng.user.anno.Evade;
import com.qianfeng.user.dto.UserRequest;
import com.qianfeng.user.dto.UserResponse;
import com.qianfeng.user.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录
 * @author Martin
 */
@Controller
public class LoginController extends BaseController{

    @Reference
    IUserService userService;


    @GetMapping("/login")
    @Evade
    public String jumpLogin(){
        return "login";
    }


    @RequestMapping(value = "/dologin")
    @Evade
    public String doLogin(UserRequest ur, HttpServletRequest request, HttpServletResponse response){

        UserRequest res = new UserRequest(ur.getUserName(),ur.getUserPass());

        if(null == userService){ //dubbo服务不可用
            return "error";
        }

        UserResponse rp = userService.login(res); //通过dubbo调用用户服务进行登录

        //登录失败跳转到登录页面
        if(null == response || StringUtils.isEmpty(rp.getUid())){
            return "login";
        }

        //按照以前，如果登录成功，是需要将用户信息保存到session中。
//        request.getSession().setAttribute("user",rp);
//        request.setAttribute("uid",rp.getUid());

        //使用token的方式，将信息保存到客户端  access_token : 注意，这里在获取的时候也需要这个值
        response.addHeader("Set-Cookie","access_token="+rp.getToken()+";Path=/;HttpOnly"); //根目录的 cookie 设置token

        return "index";
    }

    //用来测试，是否可以直接访问资源
    @RequestMapping(value = "/buy")
    public String buy(HttpServletRequest request){

        //按照以前单机登录,是从Session中获取用户信息
//        UserResponse ur = (UserResponse)request.getSession().getAttribute("user");
//        System.out.println("Session中： /buy : id " + ur.getUid());

        System.out.println("Token中：/buy : id " + getUserID());
        request.setAttribute("uid",getUserID());

        return "info";
    }

}
